<?php

namespace app\service\admin\system;

use app\model\Common;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

class MenuService
{

    /**
     * 列表
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function getList(): array
    {
        $res = Common::getAllData(MenuTable, [], ['id', 'pid', 'name', 'name_en', 'icon as icons', 'type', 'url', 'sort', 'create_time'], true, 'sort', 'asc');

        $res['data'] = getTree($res['data'], 'pid', 'children');
        return $res['data'];
    }

    /**
     * 添加
     * @param array $request
     * @return int|string
     */
    public static function add(array $request)
    {
        return Common::addData(MenuTable, $request);
    }

    /**
     * 修改
     * @param array $request
     * @return false|int
     * @throws DbException
     */
    public static function update(array $request)
    {
        if (!isset($request['id']) || !$request['id']) {
            return false;
        }
        if ((int)$request['type'] === 1) {
            $request['url'] = '';
        } else {
            $request['icon'] = '';
        }
        return Common::updateData(MenuTable, ['id' => $request['id']], $request);
    }

    /**
     * 删除
     * @param array $request
     * @return false|int|string
     * @throws DbException
     */
    public static function delete(array $request)
    {
        if (!isset($request['data']) || !$request['data']) {
            return false;
        }
        $list = [];
        foreach ($request['data'] as $v) {
            $list[] = $v['id'];
        }
        return Common::deleteData(MenuTable, ['id' => $list]);
    }

    /**
     * 树形结构列表
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function getTreeList(): array
    {
        $res = Common::getAllData(MenuTable, [], ['id', 'pid', 'name as title'], true);
        return getTree($res['data'], 'pid', 'children');
    }
}